<?php

class Models_ImageManga
{
    private static $_instance = null;
    
	private $_db;
	private $_config;
 
	/**
	 * 
	 * @param array $options
	 */
    public function __construct($options = null)
    {}
    
    /**
     * @param array $options
     * @return Models_ImageManga
     */
    public static function factory($options = null)
    {
        if (!self::$_instance) {
            self::$_instance = new self($options);
        }
        return self::$_instance;
    }
	
    public function insert($data)
    {
        $this->_db = Globals::getDbConnection('maindb', false);
        
        // Start a transaction explicitly.
        try {
            // Attempt to execute one or more queries:
            $productDetailData = array();
            /* insert table product */
            $productData = array(
                "id" => $data['id'],
                "sub_id" => $data['sub_id'],
                "image"	 => $data['image'],
                "order" => $data['order'],
            );
            	
            // 			prAli($productData);
            $result = $this->_db->insert('image_manga', $productData);
            	
            //regiter SGN leaderboard if it's point games
            	
        } catch (Exception $e) {
            $this->_db->rollBack();
            prAli($e->getMessage());
        }
        return $result;
    }
    
    public function update($data, $mainId, $subId, $imageId)
    {
        try {
            $this->_db = Globals::getDbConnection('maindb', false);
            /* update table product */
            $productData = array(
                "order" => $data['order'],
            );
//             prAli($productData);
            $result = $this->_db->update('image_manga', $productData, "id = " . $mainId . " and sub_id = " . $subId . " and image_id = " . $imageId);
            //regiter SGN leaderboard if it's point games
            	
            $this->_db->commit();
    
            return $result;
        } catch (Exception $e) {
            $this->_db->rollBack();
            pr($e->getMessage());die($e);
            return 0;
        }
    }
    
    public function selectAll($mainId, $subId, $options)
    {
        try{
            $this->_db = Globals::getDbConnection('maindb', false);
            $sql = "SELECT * ";
            $from = " from `image_manga` ";
            $where = " WHERE 1 = 1 AND image != '' AND id = {$mainId} AND sub_id = {$subId} ";
            $order = " order by `order` asc ";
            if (!empty($options['limit'])) {
                $limit = $options['limit'];
            }
//             prAli($sql.$from.$where.$order.$limit);
            $result = $this->_db->fetchAll($sql . $from . $where . $order . $limit);
            return $result;
        }
        catch(Exception $e){
            pr($e->getMessage());
        }
    }
    
    public function select($mainId, $subId, $imageId)
    {
        try{
            $this->_db = Globals::getDbConnection('maindb', false);
            $sql = "SELECT
            * ";
            $from = " from `image_manga` ";
            $where = " WHERE 1 = 1 AND image != '' AND id = {$mainId} AND sub_id = {$subId} AND image_id = {$imageId} ";
            $order = " order by order asc ";
        
            $result = $this->_db->fetchAll($sql.$from.$where.$order);// pr($sql.$from.$where.$order);
            return $result;
        }
        catch(Exception $e){
            pr($e->getMessage());
        }
    }
    
    public function totalItem($mainId, $subId)
    {
        try{
            $this->_db = Globals::getDbConnection('maindb', false);
            $sql = "SELECT count(*) as total";
            $from = " from `image_manga` ";
            $where = " WHERE 1 = 1 AND image != '' AND id = {$mainId} AND sub_id = {$subId} ";
//             prAli($sql.$from.$where);
            $result = $this->_db->fetchOne($sql . $from . $where);
//             prAli($result);
            return $result;
        }
        catch(Exception $e){
            pr($e->getMessage());
        }
    }
    
    public function delete($mainId, $subId = '0', $imageId = '')
    {
        // Start a transaction explicitly.
        $this->_db = Globals::getDbConnection('maindb', false);
		$this->_db->beginTransaction();		 
		try {	
			$query = array();
			if (!empty($mainId)) {
			    $query[] = 'id = ' . $this->_db->quote($mainId, 'INTEGER');
			}
			if (!empty($subId)) {
			    $query[] = 'sub_id = ' . $this->_db->quote($subId, 'INTEGER');
			}
			if (!empty($imageId)) {
			    $query[] = 'image_id = ' . $this->_db->quote($imageId, 'INTEGER');
			}
// 			prAli($query);
			$res = $this->_db->delete("image_manga", $query);
	        
			// If all succeed, commit the transaction and all changes
			// are committed at once.
			$this->_db->commit();
			return $res;
		 
		} catch (Exception $e) {
			// If any of the queries failed and threw an exception,
			// we want to roll back the whole transaction, reversing
			// changes made in the transaction, even those that succeeded.
			// Thus all changes are committed together, or none are.
			$this->_db->rollBack();
			prAli($e->getMessage());
			return 0;
		}	
    }
    
    function getContentHtml($url) {        
        try {
			$url = str_replace(' ', '%20', $url);
			$curl = curl_init($url);
			curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			//curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
			//curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
			curl_setopt($curl, CURLOPT_COOKIE, 'location.href;');
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            $result = curl_exec($curl);
        } catch (Exception $exc) {
            prAli($exc->getMessage());
        }
        curl_close($curl);
        
        return $result;
    }
    
    function getTagImage($content)
    {
        $res = array();
        preg_match_all('/<img[^>]*>/', $content, $res);
        return $res;
    }
    
    /**
     * Get src of tag <img>
     * @param string $url
     * @param bool $link true if $url is a link, false if file
     * @return multitype:string array link of image
     */
    function getLinkImage($url, $link = true)
    {
        if ($link) {
            $sitesHtml = $this->getContentHtml($url);
			//file_put_contents('test.html', $sitesHtml);
//             $sites_html = file_get_contents($url);
//             prAli($sites_html);
        } else {
            $sitesHtml = file_get_contents($url);
        }
        $html = new DOMDocument();
        @$html->loadHTML($sitesHtml);
        //Get all meta tags and loop through them.
        $res = array();
        /*
        foreach($html->getElementsByTagName('img') as $img) {
            $prop = $img->getAttribute('src');
//             prAli($prop);
            $res[] = $prop;
        }
         */
        $tags = $this->getTagImage($sitesHtml);
        $regexLink = '/^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$/';
        foreach($tags[0] as $tag) {
            $ele = new DOMDocument();
            @$ele->loadHTML($tag);
            $img = $ele->getElementsByTagName('img')->item(0);
            $prop = $img->getAttribute('src');
        	if (!$prop) {
        	    $prop = $img->getAttribute('tppabs');
        	}
        	if ($prop) {
                $res[] = $prop;
        	}
        }
//         prAli($res);
        return $res;
    }
    
    /**
     * Get image from url to server
     * @param string $url
     * @param string $repository
     * @return string name of image on server
     */
    function getImageFromUrl($url, $repository, $suffix = '')
    {
        try {
            if (!$suffix) {
                $suffix = time();
            }
			$url = str_replace(' ', '%20', $url);
            $filename = basename($url);
            $fileName = str_replace(' ', '', $filename);
            $extension = pathinfo($fileName, PATHINFO_EXTENSION);
            preg_match('/jpg|jpeg|gif|png|bmp/', $extension, $ext);
			$e = $ext[0];
			if (!$e) {
				$e = 'jpg';
			}
            $name = 'image_' . $suffix . '.' . $e;
            $ch = curl_init($url);
            $fp = fopen($repository . '/' . $name, 'wb');
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_exec($ch);
        } catch (Exception $exc) {
            prAli($exc->getMessage());
        }
        curl_close($ch);
        fclose($fp);
        
        if (filesize($repository . '/' . $name) > 0) {
            return $name;
        }
        
        return '';
    }
    
    /**
     * Save image from url to static
     * @param array $arrUrl array content url
     * @param string $repository path save example: 0001/Ten cua truyen
     * @return multitype:string
     */
    function saveImageToStatic($arrUrl, $repository)
    {
        $res = array();
        $suffix = time();
        foreach($arrUrl as $url) {
            //pr($repository);
            $path = $repository; 
            $name = $this->getImageFromUrl($url, $path, $suffix);
            if ($name) {
                $suffix++;
                $res[] = array('link' => $url,
					'name' => $name,
				);
            }
        }
        return $res;
    }
    
    /*
     * upload image to static
    */
    public function uploadFileToStatic($file, $ftpPath = null, $fileName = null){
        try {
            $fp = fopen($file, 'r');
            if (!$fileName) {
                $fileName = basename($file);
            }
            $conn_id = ftp_connect($this->_config->ftp->host);
            $login_result = ftp_login($conn_id, $this->_config->ftp->username, $this->_config->ftp->pwd);
            if (!$ftpPath) {
                $ftpPath = $this->_config->ftp->path;
            }
            if (!ftp_chdir($conn_id, $ftpPath)) {
                ftp_mkdir($conn_id, $ftpPath);
            }
             
            ftp_close($conn_id);
            $conn_id = ftp_connect($this->_config->ftp->host);
            $login_result = ftp_login($conn_id, $this->_config->ftp->username, $this->_config->ftp->pwd);
    
//             prAli($ftpPath);
            if (ftp_fput($conn_id, $ftpPath .'/'. $fileName, $fp, FTP_BINARY)) {
                return true;
            } else {
                throw new Exception("upload file error dsfad");
            }
            ftp_close($conn_id);
            fclose($fp);
        }catch(Exception $e){
            prAli($e);
        }
    }
}